import cv2

# frame = cv2.imread('C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\zfb.jpg')
# height_img = 640
# width_img = 480
# frame = cv2.resize(frame, (width_img, height_img))
#     # 灰度化
# frameGary = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#     # 高斯模糊
# frameBlur = cv2.GaussianBlur(frameGary, (5, 5), 1)
#     # 寻找边缘
# frameCanny = cv2.Canny(frameBlur, 50,50)
# cv2.imshow('frame',frameCanny)


# 1.调用摄像头，并灰度
cv2.namedWindow("CaptureFace")
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

# 2.创建Haar级联器
faces = cv2.CascadeClassifier('D:/Users/pyfangyao/opencv/data/haarcascades/haarcascade_frontalface_default.xml')


while cap.isOpened():
    flag, frame = cap.read()
    frame = cv2.flip(frame, 1)
    if not flag:
        break

    # 3.灰度转换
    grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 4.人脸检测，1.2和2分别为图片缩放比例和需要检测的有效像素
    face = faces.detectMultiScale(grey,1.2, 3)
    if len(face) > 0:  # 大于0则检测到人脸
        print('检测到人脸')
        for f in face:
            x, y, w, h = f
            # 框出每一张人脸
            cv2.rectangle(frame, (x, y), (x + w, y + h ), (0,0,255), 3)
    cv2.imshow("CaptureFace", frame)
    # 退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()